<?php

namespace app\modules\v1\filters;


use common\models\db\AdminUser;
use common\models\db\User;
use Yii;

/**
 *
 */
class Access extends \common\filters\BaseFilter
{
    private static $cache = null;
    const SESSION_KEY = 'PSI_SESSION_USER_ID';

    public function beforeAction($action)
    {
        if ($this->checkExcept()) {
            return true;
        }
        $userId = self::getCacheUserId($this->owner->sessionId);

        $user = $userId ? User::findOne($userId) : null;
        if (!$user) {
            if ($this->checkExcept()) {
                return true;
            }
            $this->owner->error('未登录', 4002);
        }
        $this->owner->userId = $user->user_id;
        $this->owner->user = $user;
        return true;
    }

    public static function getCache()
    {
        if (!self::$cache) {
            self::$cache = Yii::$app->getCache();
        }
        return self::$cache;
    }

    public static function setCacheUserId($sessionId, $userId)
    {
        $cache = self::getCache();
        $cache->set(self::SESSION_KEY . $sessionId, $userId, 3600 * 24 * 30);
    }

    public static function getCacheUserId($sessionId)
    {
        if (!self::getCache()->exists(self::SESSION_KEY . $sessionId)) {
            return 0;
        }
        return self::getCache()->get(self::SESSION_KEY . $sessionId);
    }

    public static function delCacheUserId($sessionId)
    {
        if (!self::getCache()->exists(self::SESSION_KEY . $sessionId)) {
            return;
        }
        self::getCache()->delete(self::SESSION_KEY . $sessionId);
    }

    public static function setCacheValue($key)
    {
        $cache = self::getCache();
        $cache->set('psi_' . $key, 1, 2);
    }

    public static function getCacheValue($key)
    {
        $cache = self::getCache();
        return $cache->get('psi_' . $key);
    }

    public static function delCacheValue($key)
    {
        if (!self::getCache()->exists('psi_' . $key)) {
            return;
        }
        self::getCache()->delete('psi_' . $key);
    }

    /**
     * @param $sessionId
     * @param $sessionKey
     */
    public static function setCacheSessionKey($sessionId, $sessionKeyInfo)
    {
        $cache = self::getCache();

        $cache->set(self::SESSION_KEY . $sessionId, serialize($sessionKeyInfo), 3600 * 24 * 30);
    }

    /**
     * @param $sessionId
     * @return int|mixed
     */
    public static function getSessionKey($sessionId)
    {
        if (!self::getCache()->exists(self::SESSION_KEY . $sessionId)) {
            return [];
        }
        return unserialize(self::getCache()->get(self::SESSION_KEY . $sessionId));
    }
}
